﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace dreamwork.mobile.app.api.Controllers
{
	public class TokenController : ControllerBase
	{
		private readonly IConfiguration _config;

		public TokenController(IConfiguration config)
		{
			_config = config;
		}

		[AllowAnonymous]
		[HttpPost]
		[Route("[action]")]
		public IActionResult CreateToken([FromBody]LoginModel login)
		{

			var tokenString = BuildToken(new UserModel { Name = "Mario Rossi", Email = "mario.rossi@domain.com" });
			return Ok(tokenString);
		}

		private string BuildToken(UserModel user)
		{
			var claims = new[] {
				new Claim(JwtRegisteredClaimNames.Sub, user.Name)
			};


			var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
			var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

			var token = new JwtSecurityToken(
			  _config["Jwt:Issuer"],
			  _config["Jwt:Issuer"],
			  claims,
			  expires: DateTime.Now.AddMinutes(30),
			  signingCredentials: creds);

			return new JwtSecurityTokenHandler().WriteToken(token);
		}

		private UserModel Authenticate(LoginModel login)
		{
			UserModel user = null;

			if (login.Username == "mario" && login.Password == "secret")
			{
				user = new UserModel { Name = "Mario Rossi", Email = "mario.rossi@domain.com" };
			}
			return user;
		}

		public class LoginModel
		{
			public string Username { get; set; }
			public string Password { get; set; }
		}

		private class UserModel
		{
			public string Name { get; set; }
			public string Email { get; set; }
			public DateTime Birthdate { get; set; }
		}
	}
}
